﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using System.IO;

namespace InputTool
{
    class HttpCompany
    {
        public static object GetRequestBody(CompanyTokenModel model)
        {
            return JsonConvert.SerializeObject(model);
        }
        public static List<string> HttpPost(string url, string name, ref string errMsg)
        {
            List<string> names = new List<string>();
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";
                request.Timeout = 20000;
                request.ProtocolVersion = HttpVersion.Version10;
                CompanyTokenModel model = new CompanyTokenModel();
                model.count = ComClassLibrary.IniFile.IniValue("GetCompanyWebApi", "count", "", ""); //"10";
                model.entnameLike = name;
                model.pageIndex = "1";
                string str = JsonConvert.SerializeObject(model);　　　　//转为字符串
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string responseStr = string.Empty;
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseStr = reader.ReadToEnd();
                }
                CompanyResultDto result = JsonConvert.DeserializeObject<CompanyResultDto>(responseStr);
                if (result.Code!=0)
                {
                    errMsg = string.Format("{0}，错误代码：{1}", result.Msg, result.Code);
                    return names;
                }
                for (int i = 0; i < result.Date.Infos.Count; i++ )
                {
                    names.Add(result.Date.Infos[i].EntName);
                }
                Company._names = names;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                names.Clear();
                return names;
            }
            return names;
        }
    }
}
